package com.zx.config.filter;

import com.zx.util.SessionDataUtil;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginFilter implements Filter {

    private static final String FILTERED_REQUEST = "@@session_context_filtered_request";

    // ① 不需要登录即可访问的URI资源
    private static final String[] INHERENT_ESCAPE_URIS = {"/user", "jpg", "js", "css", "gif", "png", "html", "login",
            "/verification", "/app", "2.ico"};

    // ② 执行过滤
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // ②-1 保证该过滤器在一次请求中只被调用一次
        if (request != null && request.getAttribute(FILTERED_REQUEST) != null) {
            chain.doFilter(request, response);
        } else {
            // ②-2 设置过滤标识，防止一次请求多次过滤
            request.setAttribute(FILTERED_REQUEST, Boolean.TRUE);
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            Object object = SessionDataUtil.getUserInfo();

            // ②-3 用户未登录, 且当前URI资源需要登录才能访问
            if (object == null && !isURILogin(httpRequest.getRequestURI(), httpRequest)) {
                // ②-4转发到登录页面
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/login/index");
                return;
            }
            chain.doFilter(request, response);
        }
    }


    /**
     * 当前URI资源是否需要登录才能访问
     *
     * @param requestURI
     * @param request
     * @return
     */
    private boolean isURILogin(String requestURI, HttpServletRequest request) {
        for (String uri : INHERENT_ESCAPE_URIS) {
            if (requestURI != null && requestURI.indexOf(uri) >= 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    @Override
    public void destroy() {

    }


}
